//
//  Networking.m
//  宏铭科技
//
//  Created by 宏铭科技 on 16/6/30.
//  Copyright © 2016年 程超. All rights reserved.
//

#import "CCNetworking.h"
#import "LoginViewController.h"
#import "UIViewController+CurrentController.h"
#import "MJ_UserLoginViewModel.h"


@implementation CCNetworking

//+ (BOOL)calulateTimeRange {
//    //获取上次的时间
//    NSDate *lastDate = [UserDefaults objectForKey:@"timeRange"];
//    if (lastDate == nil) {
//        [UserDefaults setObject:[NSDate date] forKey:@"timeRange"];
//        return YES;
//    }else {
//        NSDate *currentDate = [NSDate date];
//        NSTimeInterval start = [lastDate timeIntervalSince1970]*1;
//        NSTimeInterval end = [currentDate timeIntervalSince1970]*1;
//        NSTimeInterval value = end - start;
//        TGLog(@"time Range = %zd",(NSInteger)value);
//        [UserDefaults setObject:[NSDate date] forKey:@"timeRange"];
//        if ((NSInteger)value > 1800) {
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"登录超时，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
//
//            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [[MJ_UserMessage sharedInstance] userLogOut];
//                [UIApplication sharedApplication].keyWindow.rootViewController = [LoginViewController new];
//            }];
//            [alert addAction:action];
//            [[UIViewController currentViewController] presentViewController:alert animated:YES completion:nil];
//            return NO;
//        }else{
//            [UserDefaults setObject:[NSDate date] forKey:@"timeRange"];
//            return YES;
//        }
//    }
//}

//GET
+(NSURLSessionTask *)getWithUrl:(NSString *)UrlStr requestParams:(NSDictionary *)params successHander:(SuccessBlock)success failureHander:(FailureBlock)failure{
//    if (![self calulateTimeRange]) {
//        return nil;
//    }

    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10.0f;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"application/json",@"text/jawascript",@"text/html",@"text/plain", nil];
    [manager.requestSerializer setValue:[UserDefaults objectForKey:@"User_Cookie"] forHTTPHeaderField:@"Cookie"];
    [manager.requestSerializer setValue:@"UE-Mobile" forHTTPHeaderField:@"User-Agent"];
    NSString *url = [Base_Url stringByAppendingString:UrlStr];
    
    TGLog(@"-get-请求数据cookie = %@  || 参数：%@ || connector----%@",[UserDefaults objectForKey:@"User_Cookie"],params,url);

    NSURLSessionTask *operation = [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {

    } success:^(NSURLSessionDataTask *  task, id  responseObject) {
        if (success) {
            success(responseObject);
        }else{
            TGLog(@"%@",responseObject);
        }
        
    } failure:^(NSURLSessionDataTask *  task, NSError * error) {
        failure(error);
        TGLog(@"%@",error);
    }];
    return operation;
}

//POST
+ (NSURLSessionTask *)postWithUrl:(NSString *)UrlStr requestParams:(NSDictionary *)params successHander:(SuccessBlock)success failureHander:(FailureBlock)failure{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10.0;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"application/json",@"text/javascript",@"text/html",@"text/plain", nil];
    [manager.requestSerializer setValue:[UserDefaults objectForKey:@"User_Cookie"] forHTTPHeaderField:@"Cookie"];
    [manager.requestSerializer setValue:@"UE-Mobile" forHTTPHeaderField:@"User-Agent"];
    NSString *url = [Base_Url stringByAppendingString:UrlStr];
    
    TGLog(@"-post-请求数据cookie = %@  || 参数：%@ || connector----%@",[UserDefaults objectForKey:@"User_Cookie"],params,url);
    NSURLSessionTask *operation = [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }else{
            TGLog(@"%@",responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        
        TGLog(@"Jeemaa network error ---------------- %@",error);
        
        if ([[error userInfo][@"NSLocalizedDescription"] isEqualToString:@"The Internet connection appears to be offline."])
        {
            [TopAlertView SetUpbackgroundColor:AlertRedColor
                                   andStayTime:2.0
                                  andImageName:@"imagePlaceholder"
                                   andTitleStr:@"当前网络不可用，请检查你的网络设置"
                                 andTitleColor:[UIColor whiteColor]
                                     andCancel:NO];
        }
        else if ([[error userInfo][@"NSLocalizedDescription"] isEqualToString:@""])
        {
            [TopAlertView SetUpbackgroundColor:AlertRedColor
                                   andStayTime:2.0
                                  andImageName:@"imagePlaceholder"
                                   andTitleStr:@"返回数据错误"
                                 andTitleColor:[UIColor whiteColor]
                                     andCancel:NO];
        }
        else if (![[[error userInfo]allKeys] containsObject:@"NSLocalizedDescription"])
        {
            
            [TopAlertView SetUpbackgroundColor:AlertRedColor
                                   andStayTime:2.0 andImageName:@"imagePlaceholder"
                                   andTitleStr:@"服务器正在维护，请稍后在试"
                                 andTitleColor:[UIColor whiteColor]
                                     andCancel:NO];
        }
        else if ([[error userInfo][@"NSLocalizedDescription"] isEqualToString:@"cancelled"])
        {
            return;
        }
        else
        {
            if ([[error userInfo][@"NSLocalizedDescription"] isEqualToString:@"已取消"]) {
                return;
            }
            [TopAlertView SetUpbackgroundColor:AlertRedColor
                                   andStayTime:2.0 andImageName:@"imagePlaceholder"
                                   andTitleStr:[error userInfo][@"NSLocalizedDescription"]
                                 andTitleColor:[UIColor whiteColor]
                                     andCancel:NO];
        }
    }];
    return operation;
}



//图片上传
+ (AFHTTPSessionManager *)postWithDataUrl:(NSString *)url requestParams:(NSDictionary *)params image:(UIImage *)image imageArray:(NSArray *)imageArray Completion:(NetWorkingManagerRestTaskCompletion)completion{

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    url = [NSString stringWithFormat:@"%@",url];
    
    [session POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //多张图片
        for (int i = 0; i < imageArray.count; i ++) {
            UIImage *updateImage = imageArray[i];
            [formData appendPartWithFileData:UIImagePNGRepresentation(updateImage) name:[NSString stringWithFormat:@"idCards"] fileName:@"test.png" mimeType:@"image/png"];
        }
        //单张图片
        UIImage *uploadImage = image;
        [formData appendPartWithFileData:UIImagePNGRepresentation(uploadImage) name:@"head" fileName:@"test.png" mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error;
        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        TGLog(@"--------------------------------------------------\n返回结果%@\n%@\n--------------------------------------------------",url,responseDic);
        BOOL type = [[responseDic valueForKey:@"success"] boolValue];
        if (completion) {
            if (type) {
                completion(responseDic , error);
            }
            else {
                NSDictionary * userInfo = @{NSLocalizedDescriptionKey : [responseDic valueForKey:@"message"]};
                NSError * error = [NSError errorWithDomain:NSURLErrorDomain
                                                      code:NSURLErrorNetworkConnectionLost
                                                  userInfo:userInfo];
                completion(nil , error);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        TGLog(@"--------------------------------------------------\n错误%@\n%@\n--------------------------------------------------",url,error);
        if (completion) { completion(nil , error); }
    }];
    
    return session;
}

+ (void)uploadWithParameter:(NSDictionary *)parameter
                           data:(NSData *)data
                       progress:(ProgressBlock)progressBlock
                  successHander:(SuccessBlock)success
                  failureHander:(FailureBlock)failure{
    
    NSString *url = [[Base_Url stringByAppendingString:userManager.urlCategate] stringByAppendingString:uploadFile_connector];
    NSMutableURLRequest* formRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    //将参数拼接到header里面
    for (NSInteger i = 0; i < parameter.allKeys.count; ++ i) {
        NSString *key = parameter.allKeys[i];
        NSString *value;
        if ([key isEqualToString:@"name"]) {//如果文件名带有中文就转换为utf-8，不然header就为空
            value = [parameter[key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }else{
            value = [NSString stringWithFormat:@"%@",parameter[key]];
        }
        [formRequest setValue:value forHTTPHeaderField:key];
    }
    [formRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [formRequest setValue:[UserDefaults objectForKey:@"User_Cookie"] forHTTPHeaderField:@"Cookie"];
    [formRequest setValue:@"UE-Mobile" forHTTPHeaderField:@"User-Agent"];
    [formRequest setTimeoutInterval:60];
    [formRequest setHTTPMethod:@"POST"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer= [AFJSONResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:
                                                  @"application/json",
                                                  @"text/json",
                                                  @"text/javascript",
                                                  @"text/html",
                                                  @"text/plain",nil]];
    
    TGLog(@"-post-请求数据参数：\n %@ \n connector--- %@ \n cookie = %@",parameter,url,[UserDefaults objectForKey:@"User_Cookie"]);
    NSURLSessionUploadTask *dataTask = [manager uploadTaskWithRequest:formRequest fromData:data progress:^(NSProgress * _Nonnull uploadProgress) {
        //设置进度
        CGFloat progress = (CGFloat)uploadProgress.completedUnitCount/(CGFloat)uploadProgress.totalUnitCount;
        progressBlock(progress);

    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        if (!error) {
            success(responseObject);
        }else{
            failure(error);
            TGLog(@"%@",error);
        }
    }];
    [dataTask resume];
}

@end
